<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Tree,
  TreeSelect,
} from 'ant-design-vue';

const loading = ref(false);
const roleList = ref<any[]>([]);
const permissionTree = ref<any[]>([]);
const userList = ref<any[]>([]);
const showRoleModal = ref(false);
const showPermissionModal = ref(false);
const currentRole = ref<any>(null);

const roleForm = ref({
  id: '',
  name: '',
  code: '',
  description: '',
  permissions: [],
});

const permissionForm = ref({
  id: '',
  name: '',
  code: '',
  type: '',
  resource: '',
  actions: [],
});

// 权限类型选项
const permissionTypeOptions = [
  { label: '菜单权限', value: 'MENU' },
  { label: '功能权限', value: 'FUNCTION' },
  { label: '数据权限', value: 'DATA' },
  { label: 'API权限', value: 'API' },
];

// 资源类型选项
const resourceTypeOptions = [
  { label: '资源目录', value: 'CATALOG' },
  { label: '排期管理', value: 'SCHEDULING' },
  { label: '占用结算', value: 'OCCUPANCY' },
  { label: '维护采购', value: 'MAINTENANCE' },
  { label: '技术资源', value: 'TECHNICAL' },
  { label: '系统设置', value: 'SETTINGS' },
];

// 操作类型选项
const actionOptions = [
  { label: '查看', value: 'VIEW' },
  { label: '创建', value: 'CREATE' },
  { label: '编辑', value: 'EDIT' },
  { label: '删除', value: 'DELETE' },
  { label: '导出', value: 'EXPORT' },
  { label: '审批', value: 'APPROVE' },
];

// 表格列定义
const roleColumns = [
  {
    title: '角色名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '角色编码',
    dataIndex: 'code',
    key: 'code',
    width: 120,
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    width: 200,
  },
  {
    title: '用户数量',
    dataIndex: 'userCount',
    key: 'userCount',
    width: 100,
  },
  {
    title: '权限数量',
    dataIndex: 'permissionCount',
    key: 'permissionCount',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right' as const,
  },
];

// 加载角色数据
const loadRoles = async () => {
  loading.value = true;
  try {
    // 模拟角色数据
    const mockRoles = [
      {
        id: '1',
        name: '系统管理员',
        code: 'ADMIN',
        description: '拥有系统所有权限',
        userCount: 3,
        permissionCount: 156,
        status: 'ACTIVE',
        permissions: ['all'],
      },
      {
        id: '2',
        name: '资源管理员',
        code: 'RESOURCE_MANAGER',
        description: '负责资源目录和排期管理',
        userCount: 8,
        permissionCount: 89,
        status: 'ACTIVE',
        permissions: ['catalog', 'scheduling', 'view'],
      },
      {
        id: '3',
        name: '财务人员',
        code: 'FINANCE',
        description: '负责占用结算和财务管理',
        userCount: 5,
        permissionCount: 67,
        status: 'ACTIVE',
        permissions: ['occupancy', 'settlement', 'view'],
      },
      {
        id: '4',
        name: '维护人员',
        code: 'MAINTENANCE',
        description: '负责维护和采购管理',
        userCount: 12,
        permissionCount: 45,
        status: 'ACTIVE',
        permissions: ['maintenance', 'purchase', 'view'],
      },
      {
        id: '5',
        name: '普通用户',
        code: 'USER',
        description: '基础查看权限',
        userCount: 25,
        permissionCount: 12,
        status: 'ACTIVE',
        permissions: ['view'],
      },
    ];

    roleList.value = mockRoles;
  } catch (error) {
    console.error('加载角色数据失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 加载权限树
const loadPermissionTree = async () => {
  try {
    // 模拟权限树数据
    const mockTree = [
      {
        title: '资源目录管理',
        key: 'catalog',
        children: [
          {
            title: '业务资源',
            key: 'catalog-business',
            children: [
              { title: '查看', key: 'catalog-business-view' },
              { title: '创建', key: 'catalog-business-create' },
              { title: '编辑', key: 'catalog-business-edit' },
              { title: '删除', key: 'catalog-business-delete' },
            ],
          },
          {
            title: '技术资源',
            key: 'catalog-technical',
            children: [
              { title: '查看', key: 'catalog-technical-view' },
              { title: '创建', key: 'catalog-technical-create' },
              { title: '编辑', key: 'catalog-technical-edit' },
              { title: '删除', key: 'catalog-technical-delete' },
            ],
          },
        ],
      },
      {
        title: '排期管理',
        key: 'scheduling',
        children: [
          { title: '查看排期', key: 'scheduling-view' },
          { title: '创建排期', key: 'scheduling-create' },
          { title: '编辑排期', key: 'scheduling-edit' },
          { title: '删除排期', key: 'scheduling-delete' },
          { title: '冲突检测', key: 'scheduling-conflict' },
        ],
      },
      {
        title: '占用结算',
        key: 'occupancy',
        children: [
          { title: '查看占用', key: 'occupancy-view' },
          { title: '创建占用', key: 'occupancy-create' },
          { title: '编辑占用', key: 'occupancy-edit' },
          { title: '结算管理', key: 'occupancy-settlement' },
        ],
      },
      {
        title: '维护采购',
        key: 'maintenance',
        children: [
          { title: '维护计划', key: 'maintenance-plan' },
          { title: '维护记录', key: 'maintenance-record' },
          { title: '采购申请', key: 'purchase-apply' },
          { title: '采购审批', key: 'purchase-approve' },
        ],
      },
      {
        title: '系统设置',
        key: 'settings',
        children: [
          { title: '角色管理', key: 'settings-role' },
          { title: '权限管理', key: 'settings-permission' },
          { title: '用户管理', key: 'settings-user' },
          { title: '系统配置', key: 'settings-config' },
        ],
      },
    ];

    permissionTree.value = mockTree;
  } catch (error) {
    console.error('加载权限树失败:', error);
  }
};

// 创建角色
const createRole = async () => {
  try {
    const newRole = {
      id: Date.now().toString(),
      name: roleForm.value.name,
      code: roleForm.value.code,
      description: roleForm.value.description,
      userCount: 0,
      permissionCount: roleForm.value.permissions.length,
      status: 'ACTIVE',
      permissions: roleForm.value.permissions,
    };

    roleList.value.push(newRole);
    message.success('角色创建成功');
    showRoleModal.value = false;
    resetRoleForm();
  } catch (error) {
    message.error('创建失败');
  }
};

// 编辑角色
const editRole = (role: any) => {
  currentRole.value = role;
  Object.assign(roleForm.value, role);
  showRoleModal.value = true;
};

// 删除角色
const deleteRole = (roleId: string) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个角色吗？',
    onOk: () => {
      roleList.value = roleList.value.filter((role) => role.id !== roleId);
      message.success('删除成功');
    },
  });
};

// 分配权限
const assignPermissions = (role: any) => {
  currentRole.value = role;
  roleForm.value.permissions = role.permissions;
  showPermissionModal.value = true;
};

// 保存权限分配
const savePermissions = async () => {
  try {
    if (currentRole.value) {
      currentRole.value.permissions = roleForm.value.permissions;
      currentRole.value.permissionCount = roleForm.value.permissions.length;
    }
    message.success('权限分配成功');
    showPermissionModal.value = false;
  } catch (error) {
    message.error('保存失败');
  }
};

// 重置表单
const resetRoleForm = () => {
  roleForm.value = {
    id: '',
    name: '',
    code: '',
    description: '',
    permissions: [],
  };
  currentRole.value = null;
};

// 辅助函数
const getStatusColor = (status: string) => {
  return status === 'ACTIVE' ? 'green' : 'red';status
};

const getStatusLabel = (status: string) => {
  return status === 'ACTIVE' ? '启用' : '禁用';status
};

onMounted(() => {
  loadRoles();
  loadPermissionTree();
});
</script>

<template>
  <div class="permission-control">
    <!-- 角色管理 -->
    <Card title="角色管理" :bordered="false" style="margin-bottom: 16px">
      <div class="table-toolbar">
        <Space>
          <Button type="primary" @click="showRoleModal = true">
            <IconifyIcon icon="mdi:plus" />
            创建角色
          </Button>
        </Space>
      </div>

      <Table
        :columns="roleColumns"
        :data-source="roleList"
        :loading="loading"
        row-key="id"
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="editRole(record)">
                编辑
              </Button>
              <Button
                type="link"
                size="small"
                @click="assignPermissions(record)"
              >
                分配权限
              </Button>
              <Button type="link" size="small" @click="deleteRole(record.id)">
                删除
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 创建/编辑角色弹窗 -->
    <Modal
      v-model:open="showRoleModal"
      :title="roleForm.id ? '编辑角色' : '创建角色'"
      width="600px"
      @ok="createRole"
    >
      <Form :model="roleForm" layout="vertical">
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="角色名称" required>
              <Input
                v-model:value="roleForm.name"
                placeholder="请输入角色名称"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="角色编码" required>
              <Input
                v-model:value="roleForm.code"
                placeholder="请输入角色编码"
              />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="角色描述">
          <Input.TextArea
            v-model:value="roleForm.description"
            placeholder="请输入角色描述"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 权限分配弹窗 -->
    <Modal
      v-model:open="showPermissionModal"
      title="分配权限"
      width="800px"
      @ok="savePermissions"
    >
      <div class="permission-assignment">
        <div class="role-info">
          <h4>角色：{{ currentRole?.name }}</h4>
          <p>{{ currentRole?.description }}</p>
        </div>

        <div class="permission-tree">
          <h4>权限树</h4>
          <Tree
            v-model:checked-keys="roleForm.permissions"
            :tree-data="permissionTree"
            checkable
            :default-expand-all="true"
            :check-strictly="false"
          />
        </div>
      </div>
    </Modal>
  </div>
</template>

<style scoped>
.permission-control {
  padding: 20px;
}

.table-toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.permission-assignment {
  padding: 16px;
}

.role-info {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.role-info h4 {
  margin: 0 0 8px 0;
  color: #1890ff;
}

.role-info p {
  margin: 0;
  color: #666;
}

.permission-tree {
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  padding: 16px;
}

.permission-tree h4 {
  margin: 0 0 16px 0;
  color: #333;
}
</style>
